//如果在规定长度就true
function checkLength($str, $min, $max) {
	if ($str.length > $min && $str.length < $max) {
		return true;
	} else {
		return false;
	}
}

function checkSpace($str) {
	$reg = /[\n\s*\r]/;
	if ($reg.test($str)) {
		return true;
	} else {
		return false;
	}
}

//包含中文就true
function checkCN($str) {
	$reg = /[\u4e00-\u9fa5]+/ui;
	if ($reg.test($str)) {
		return true;
	} else {
		return false;
	}
}

//如果是英文开头就true
function checkEs($str) {
	$reg = /[a-zA-Z]+[0-9]*/; //必须是英文开头
	if ($reg.test($str)) {
		return true;
	} else {
		return false;
	}
}

//如果有特殊字符就true
function checkSpecial($str) {
	$reg = /[`~!@#$%^&*()_\-+=<>?:"{}|,.\/;'\\[\]·~！@#￥%……&*（）——\-+={}|《》？：“”【】、；‘'，。、]/im;
	//$reg=/[^u4e00-u9fa5w]+/ig;
	if ($reg.test($str)) {
		return true;
	} else {
		return false;
	}
}

//是英文和数字就true
function checkEN($str) {
	$reg = /[\w]+/g;
	if ($reg.test($str)) {
		return true;
	} else {
		return false;
	}
}

//正则检测,如果匹配正则j就true
function checkReg($reg, $str) {
	if ($reg.test($str)) {
		return true;
	} else {
		return false;
	}
}

function copyToClipBoard($str) { //拷贝剪贴板
	const input = document.createElement('input');
	input.setAttribute('readonly', 'readonly');
	input.setAttribute('value', $str);
	document.body.appendChild(input);
	input.setSelectionRange(0, 9999);
	input.select();
	if (document.execCommand('copy')) {
		document.execCommand('copy');
		console.log('复制成功');
	}
	document.body.removeChild(input);
}

// function checkusername(that) {
// 	let username = localStorage.getItem('ms_username');
// 	//let username="test";
// 	if (!username) {
// 		this.$alert('非法操作', '消息提示', {
// 			confirmButtonText: '确定'
// 		});
// 		this.$router.push('/login');
// 	}
// 	that.$axios.post("http://api.xuejing.pro/admin/admin/verify", {
// 		username
// 	}).then(
// 		function(res) {
// 			console.log(res);
// 			if (res.data.code == -1) {
// 				that.$alert('非法操作', '消息提示', {
// 					confirmButtonText: '确定'
// 				});
// 				that.$router.push('/login');
// 			}
// 		},
// 		function(err) {
// 			that.$alert('非法操作', '消息提示', {
// 				confirmButtonText: '确定'
// 			});
// 			that.$router.push('/login');
// 		});
// }

function base64show(res) { //生成base64图片
	var binary = "";
	var bytes = new Uint8Array(res);
	var len = bytes.byteLength;
	for (var i = 0; i < len; i++) {
		binary += String.fromCharCode(bytes[i]);
	}
	return "data:img/png;base64," + window.btoa(binary);
}


function order_number() { //生成订单号
	let vNow = new Date();
	let sNow = "";
	sNow += String(vNow.getFullYear());
	sNow += String(vNow.getMonth() + 1).padStart(2,0);
	sNow += String(vNow.getDate()).padStart(2,0);
	sNow += String(vNow.getHours()).padStart(2,0);
	sNow += String(vNow.getMinutes()).padStart(2,0);
	sNow += String(vNow.getSeconds()).padStart(2,0);
	sNow += String(vNow.getMilliseconds()).padStart(4,0);
	sNow += randomnumber();
	return sNow;
}

function randomnumber($length=7){
	let $chars="0123456789";
	let $str="";
	for(let $i=0;$i<$length;$i++){
	$str+=$chars.substr(Math.floor(Math.random()*$chars.length),1);
	}
	return $str;
}

//-----------------------------------------时间处理
function jsDateFormatter(date) { //毫秒转Y-m-d H:i:s格式
return new Promise(resolve => {
	var seperator1 = "-";
	var seperator2 = ":";
	var month = date.getMonth() + 1;
	var strDate = date.getDate();
	var strHours = date.getHours();
	var strMinutes = date.getMinutes();
	var strSeconds = date.getSeconds();
	if (month >= 1 && month <= 9) {
		month = "0" + month;
	}
	if (strDate >= 0 && strDate <= 9) {
		strDate = "0" + strDate;
	}
	if (strHours >= 0 && strHours <= 9) {
		strHours = "0" + strHours;
	}
	if (strMinutes >= 0 && strMinutes <= 9) {
		strMinutes = "0" + strMinutes;
	}
	if (strSeconds >= 0 && strSeconds <= 9) {
		strSeconds = "0" + strSeconds;
	}
	var currentdate = date.getFullYear() + seperator1 + month + seperator1 + strDate + " " + strHours + seperator2 +
		strMinutes + seperator2 + strSeconds;
	resolve(currentdate);
	});
}

//毫秒转Y-m-d H:i:s格式
function getSpeTime(timeStr) {
    // timeStr是毫秒值
    // 获取年份
		var year=new Date(timeStr).getFullYear();
    //获取月份，获取的月份比实际小1，所以需要+1
		var month=new Date(timeStr).getMonth()+1;
    //获取日
		var date=new Date(timeStr).getDate();
    //获取时
		var hours=new Date(timeStr).getHours();
    //获取分
		var minutes=new Date(timeStr).getMinutes();
		if (month >= 1 && month <= 9) {
			month = "0" + month;
		}
		if (date >= 0 && date <= 9) {
			date = "0" + date;
		}
		if (hours >= 0 && hours <= 9) {
			hours = "0" + hours;
		}
        if (minutes < 10) {
			minutes = '0' + minutes
		}
		//获取秒
		var seconds=new Date(timeStr).getSeconds();
		if (seconds < 10) {
			seconds = '0' + seconds
		}
     //组合格式为年-月-日 时：分：秒（2022-6-6 12:12:12）
		return year+"-"+month+"-"+date+" "+hours+":"+minutes+":"+seconds;
	}

	//年-月-日 时：分：秒（2022-6-6 12:12:12）转 毫秒
	function getHTime(date){
	let startDate=date.replace(new RegExp("-","gm"),"/");
	let startDateM = (new Date(startDate)).getTime(); 
	return startDateM;
	}

function formatDuring(millisecond) {
		var days = parseInt(millisecond / (1000 * 60 * 60 * 24));
		var hours = parseInt((millisecond % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60));
		var minutes = parseInt((millisecond % (1000 * 60 * 60)) / (1000 * 60));
		var seconds = (millisecond % (1000 * 60)) / 1000;
		return days + " 天 " + hours + " 小时 " + minutes + " 分钟 " + seconds + " 秒 ";
		}
//---------------------------------------------------------时间处理

//建立一個可存取到該file的url
function getObjectURL(file) { //得到缓存图片
	var url = null;
	if (window.createObjectURL != undefined) { // basic
		url = window.createObjectURL(file);
	} else if (window.URL != undefined) { // mozilla(firefox)
		url = window.URL.createObjectURL(file);
	} else if (window.webkitURL != undefined) { // webkit or chrome
		url = window.webkitURL.createObjectURL(file);
	}
	return url;
}


//格式化视频时长
function getTime(duration) {
	let hour = parseInt(duration / 3600) + '';
	let minute = parseInt(duration % 3600 / 60) + '';
	let second = parseInt(duration % 3600 % 60 % 60) + '';
	let time = hour.padStart(2, '0') + ':' + minute.padStart(2, '0') + ':' + second.padStart(2, '0');
	return time;
}

//截取视频第几帧作为封面
function chooseVideo(file, sec) {
	return new Promise(resolve => {
		var blob = new Blob([file]), // 文件转化成二进制文件
			url = getObjectURL(blob); //转化成url
		console.log('img',url)
		//创建video标签
		var videoElement = document.createElement("video");
		videoElement.src = url
		videoElement.currentTime = sec;
		videoElement.addEventListener("canplay", function() {
			var canvas = document.createElement("canvas");
			canvas.width = videoElement.videoWidth;
			canvas.height = videoElement.videoHeight;
			canvas.getContext("2d").drawImage(videoElement, 0, 0, canvas.width, canvas.height);
			var firstFrame = canvas.toDataURL("image/png"); //第一帧图片url
			resolve(firstFrame);
		})
	})
}

// 设置图片缩放比例
function imageScale(width, originWidth, originHeight) {
	const scaleRatio = width / originWidth;
	const scaleHeight = scaleRatio * originHeight;
	return [width, scaleHeight];
}
// 获取视频第一帧作为封面图 blob格式图片
function getVideoPoster(file, scaleWidth, quality = 0.5) {
	return new Promise((resolve, reject) => {
		const reader = new FileReader();
		reader.readAsDataURL(file);
		reader.onload = (e) => {
			let video = document.createElement("video");
			video.src = e.target.result;
			video.onloadeddata = () => {
				const canvas = document.createElement("canvas");
				const [width, height] = imageScale(
					scaleWidth,
					video.videoWidth,
					video.videoHeight
				);
				canvas.width = width;
				canvas.height = height;
				const ctx = canvas.getContext("2d");
				ctx.fillRect(0, 0, width, height);
				ctx.drawImage(video, 0, 0, width, height);
				ctx.imageSmoothingEnabled = false;
				canvas.toBlob(
					async (blob) => {
						let url = window.URL.createObjectURL(blob);
						video.pause();
						video = null;
						resolve(url);
					},
					"image/jpeg",
					0.5
				);
			};
			video.onerror = () => {
				video.pause();
				video = null;
				reject();
			};
			video.muted = false;
			// video.play();
		};
	});
}

//获得视频分辨率和时间
function getVideoPlayerInfo(file) {
	return new Promise(resolve => {
		const videoElement = document.createElement('video');
		videoElement.src = getObjectURL(file);
		videoElement.addEventListener('loadedmetadata', function() {
			resolve({
				duration: videoElement.duration,
				width: videoElement.videoWidth,
				height: videoElement.videoHeight
			});
		});
	});
}

//获得视频分辨率和时间
function getAudioPlayerInfo(file) {
	return new Promise(resolve => {
		const audioElement = document.createElement('audio');
		audioElement.src = getObjectURL(file);
		audioElement.addEventListener('loadedmetadata', function() {
			resolve({
				duration: audioElement.duration,
			});
		});
	});
}

//获得上传BASE64编码
function getBase64(file) { //为了得到上传分辨率
	const reader = new FileReader();
	reader.readAsDataURL(file);
	return new Promise((resolve) => {
		reader.onload = () => {
			resolve(reader.result);
		};
	});
}

//得到图片上传的宽高
function getImgPx(img) { //味蕾得到上传分辨率
	const image = new Image();
	image.src = img;
	return new Promise((resolve) => {
		image.onload = () => {
			const width = image.width;
			const height = image.height;
			resolve({
				width,
				height
			});
		};
	});
}

//检测是不是微信浏览器
function isWeixin(){
    return navigator.userAgent.indexOf("MicroMessenger")>0;
}

function getSearchParams () {
  const params = {}
  window.location.search &&
    // eslint-disable-next-line no-useless-escape
    window.location.search.match(/\??&?([^\?&]+)=([^\?&]+)/g).forEach((str) => {
      str = str.slice(1)
      var arrs = str.split('=')
      params[arrs[0]] = arrs[1]
    })
  return params
}

//下载文件
function Download(url, title) {
	var x = new XMLHttpRequest();
	x.open("GET", url, true);
	x.responseType = 'blob';
	x.onload = function () {
		const url = window.URL.createObjectURL(x.response)
		const eleLink = document.createElement("a");
		eleLink.href = url;
		eleLink.download = `${title}`;
		eleLink.style.display = "none";
		document.body.appendChild(eleLink);
		eleLink.click();
		document.body.removeChild(eleLink);
	}
	x.send();
}


//去除空数组
function trimSpace(array){  
    for(var i = 0 ;i<array.length;i++)  
    {  
       //这里为过滤的值
        if(array[i] == " " || array[i] == null || typeof(array[i]) == "undefined" || array[i] == '  ' )  
        {  
            array.splice(i,1);
            i= i-1;
        }  
    }  
    return array;  
} 


function removeSameArray(arr,name){   // 数组去重
	for (let i = 0;i < arr.length-1;i++) {
		for (let j = i+1;j < arr.length;j++){
			if (name) {
				if (arr[i][name] == arr[j][name]) {
					arr.splice(j,1);
					j--;
				}
			} else {
				if (arr[i] == arr[j]) {
					arr.splice(j,1);
					j--;
				}
			}			
		}
	}
	return arr;
}
